package com.ohuang.jiaxiaotong.Activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.example.myhttp.CallBackString;
import com.example.myhttp.Ihttp;
import com.ohuang.jiaxiaotong.MyHttpURL;
import com.ohuang.jiaxiaotong.R;
import com.ohuang.jiaxiaotong.Util.Ohuang;
import com.ohuang.jiaxiaotong.Util.Sys;
import com.ohuang.jiaxiaotong.base.BaseAc;
import com.ohuang.jiaxiaotong.entity.ClassMember;
import com.ohuang.jiaxiaotong.entity.EventMsg;
import com.ohuang.jiaxiaotong.entity.User;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.POST;
import retrofit2.http.QueryMap;

public class JoinClassmemberActivity extends BaseAc {
    private ListView listView;
    private Button button_join;
    private CommonAdapter commonAdapter;
    private List<ClassMember> mData;
    private String className;
    private User user;
    private final static int JOIN_OK = 1, JOIN_ERROR = 2, NET_ERROR = 3, NET_OTHER = 4;
    private Dialog dialogLoading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_join_classmember);
        Intent intent = getIntent();
        className = intent.getStringExtra("className");
        EventBus.getDefault().register(this);//注册EventBus
        setTitle(className);
        Ohuang.changeStatusBarTextImgColor(this, true);
        Objects.requireNonNull(getSupportActionBar()).setHomeAsUpIndicator(R.mipmap.icon_goback);//设置ActionBar返回按钮

        listView = findViewById(R.id.listView_joinClassMember);
        button_join = findViewById(R.id.btn_join_joinClassMember);
        httpGetClassMember(className);

        button_join.setOnClickListener(new View.OnClickListener() {//点击加入按钮
            @Override
            public void onClick(View v) {
                if (Sys.isClick()) {
                    if (user != null) {
                        dialogLoading = Ohuang.dialogLoadingshow(JoinClassmemberActivity.this, "正在加入中");

                        HttpJoin();

                    }
                }
            }
        });
    }

    //加入请求
    private void HttpJoin() {
        HashMap<String, String> map = new HashMap<>();
        map.put("className", className);
        map.put("username", user.getUsername());
        map.put("role", user.getRole());

        Ihttp.getInstance().post(MyHttpURL.mainUrl + "user/joinClass", map, new CallBackString() {
            @Override
            public void success(String ojb) {
                String code = ojb;
                if ("success".equals(code)) {
                    myHandler.sendEmptyMessage(JOIN_OK);
                } else if ("error".equals(code)) {
                    myHandler.sendEmptyMessage(JOIN_ERROR);
                } else {
                    myHandler.sendEmptyMessage(NET_OTHER);
                }
            }

            @Override
            public void fail(String s) {
                myHandler.sendEmptyMessage(NET_ERROR);
            }
        });


    }

    @SuppressLint("HandlerLeak")
    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case NET_ERROR:
                    dialogLoading.dismiss();
                    Toast.makeText(JoinClassmemberActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    break;
                case NET_OTHER:
                    dialogLoading.dismiss();
                    Toast.makeText(JoinClassmemberActivity.this, "返回值错误", Toast.LENGTH_SHORT).show();
                    break;
                case JOIN_OK:
                    dialogLoading.dismiss();
                    EventBus.getDefault().post(new EventMsg(1, "加入班级 需要更新班级列表信息"));//需要在ClassFragment和Class2Fragment中处理
                    Ohuang.dialogshow(JoinClassmemberActivity.this, "加入成功", "你已成功加入班级", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finish();
                        }
                    });
                    break;
                case JOIN_ERROR:
                    dialogLoading.dismiss();
                    Ohuang.dialogshow(JoinClassmemberActivity.this, "加入失败", "你已经是该班级成员了,请勿重复添加");
                    break;

            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //eventBus获取User
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void GetUserEventBus(User user) {
        this.user = user;
    }


    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == android.R.id.home) {//左上角返回按钮
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    //获取班级成员
    private void httpGetClassMember(String s) {
//创建Retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(MyHttpURL.mainUrl + "user/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        GithubService service = retrofit.create(GithubService.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("className", s);
        service.getClassMember(map).enqueue(new Callback<List<ClassMember>>() {
            @Override
            public void onResponse(Call<List<ClassMember>> call, Response<List<ClassMember>> response) {
                mData = response.body();
                commonAdapter = new CommonAdapter(JoinClassmemberActivity.this, R.layout.list_classmember_item, mData) {
                    @Override
                    protected void convert(ViewHolder viewHolder, Object item, int position) {
                        String code = ((ClassMember) item).getRole();
                        if ("0".equals(code)) {
                            viewHolder.setText(R.id.txt_list_classmember, "老师：" + ((ClassMember) item).getUsername());
                            viewHolder.setImageResource(R.id.img_list_classmember, R.drawable.dra_teacher);
                        } else {
                            viewHolder.setText(R.id.txt_list_classmember, "家长：" + ((ClassMember) item).getUsername());
                            viewHolder.setImageResource(R.id.img_list_classmember, R.drawable.img_icon);
                        }
                    }
                };
                listView.setAdapter(commonAdapter);
            }

            @Override
            public void onFailure(Call<List<ClassMember>> call, Throwable t) {

            }
        });
    }

    interface GithubService {
        //https://api.github.com/repos/{owner}/{repo}/contributors
        @POST("findAllUser")
        Call<List<ClassMember>> getClassMember(@QueryMap HashMap<String, String> deviceInfo);
    }
}
